package com.jiangnan.warehouse_management.utils;

import org.springframework.stereotype.Component;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.nio.charset.StandardCharsets;

@Component
public class MD5Utils {
    
    private static final String SALT = "warehouse_management"; // 加盐值，增加密码安全性
    
    /**
     * 对密码进行MD5加密
     * @param password 原始密码
     * @return 加密后的密码
     */
    public String encrypt(String password) {
        if (password == null || password.isEmpty()) {
            throw new IllegalArgumentException("密码不能为空");
        }
        
        try {
            // 将密码和盐值组合
            String saltedPassword = password + SALT;
            
            // 创建MessageDigest实例并指定算法为MD5
            MessageDigest md = MessageDigest.getInstance("MD5");
            
            // 将密码字符串转换为字节数组并进行加密
            byte[] bytes = md.digest(saltedPassword.getBytes(StandardCharsets.UTF_8));
            
            // 将字节数组转换为十六进制字符串
            StringBuilder result = new StringBuilder();
            for (byte b : bytes) {
                String hex = Integer.toHexString(0xff & b);
                if (hex.length() == 1) {
                    result.append('0');
                }
                result.append(hex);
            }
            
            return result.toString();
        } catch (NoSuchAlgorithmException e) {
            throw new RuntimeException("MD5加密失败", e);
        }
    }
    
    /**
     * 验证密码是否正确
     * @param inputPassword 输入的密码
     * @param encryptedPassword 加密后的密码
     * @return 是否匹配
     */
    public boolean verify(String inputPassword, String encryptedPassword) {

        // System.out.println("encryptedPassword: " + encryptedPassword);
        if (inputPassword == null || encryptedPassword == null) {
            return false;
        }
        
        String encryptedInput = encrypt(inputPassword);
        // System.out.println("inputPassword: " + encryptedInput);
        return encryptedInput.equals(encryptedPassword);
    }
}